<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH.'libraries/ApiController.php';
class Articlecategory extends ApiController
{
	public function __construct()
	{
	    parent::__construct();
	}

	function index(){

	}

	
	public function list_by_page(){
		$token=123;//$this->verifyToken();
		if($token){
			$list=$user=$this->db->select("*")->get("article_category")->result_array();
			$menus=$this->buildTree($list,-1);
 			$this->WRITE("code",1);
			$this->WRITE("list",$menus);
			$this->WRITE("msg","success");
			$this->RESPONSE();
		}
	}
	
	//新增分类时，获取下拉表里的分类
	public function list_array(){
		$token=$this->verifyToken();
		if($token){
			$list=$user=$this->db->select("*")->get("article_category")->result_array();
    		$mlist=$this->buildList($list,-1);
			$this->WRITE("code",1);
			$this->WRITE("list",$mlist);
			$this->WRITE("msg","success");
			$this->RESPONSE();
		}
	}
	
	public function create(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			  ['pid',True,"父级id"],
			  ['title',True,"分类名称"],
			  ["desc",False,"分类简介",""],
			  ["order",True,"排序"],
			  ["status",True,'排序']
			],'post');
			
			$res=$this->db->insert("article_category",$data);
			if($res){
				$this->WRITE("code",1);
				$this->WRITE("msg","success");
				$this->RESPONSE();
			}else{
				$this->WRITE("code",1);
				$this->WRITE("msg","添加分类失败");
				$this->RESPONSE();
			}
		}
	}
	
	public function update(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			  ["catid",True,"分类id"],
			  ['pid',True,"父级id"],
			  ['title',True,"分类名称"],
			  ["desc",False,"分类简介",""],
			  ["order",True,"排序"],
			  ["status",True,'排序']
			],'post');
			
			$this->db->where("catid",$data["catid"]);
			$res=$this->db->update("article_category",$data);
			if($res){
				$this->WRITE("code",1);
				$this->WRITE("msg","编辑分类成功!");
				$this->RESPONSE();
			}else{
				$this->WRITE("code",1);
				$this->WRITE("msg","编辑分类失败");
				$this->RESPONSE();
			}
		}
		
	}
	
	protected function buildList($cats,$pid=-1,$lv=0){
		$tree=[];
		foreach($cats as $cat){
			if($cat["pid"]==$pid){
				$cat["level"]=$lv;
				$tree[]=$cat;
				$children=$this->buildList($cats,$cat["catid"],$lv+1);
				usort($children,function($a,$b){
					return $a["order"]<=$b["order"];
				});
				$tree=array_merge($tree,$children);
			}
		}
		return $tree;
	} 
 
	protected function buildTree($cats,$pid=-1){
		$tree=[];
		foreach($cats as $cat){
			if($cat["pid"]==$pid){
					$children=$this->buildTree($cats,$cat["catid"]);
					usort($children,function($a,$b){
						return $a["order"]<=$b["order"];
					});
					if($children){
						$cat["children"]=$children;
					}
				$tree[]=$cat;
			}
		}
		usort($tree,function($a,$b){
			return $a["order"]<=$b["order"];
		});
		return $tree;
	} 
	
	

}